package sketch.doc;

import java.awt.Graphics2D;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class SketchContainer {

	private static int strokeId = 0;

	public static int getStrokeId() {
		return strokeId++;
	}

	public static void resetStrokeId() {
		strokeId = 0;
	}

	private static SketchContainer instance = null;

	public static SketchContainer get() {
		if (instance == null) {
			instance = new SketchContainer();
		}
		return instance;
	}

	private SketchContainer() {
		init();
	}

	private void init() {
		sketch = null;
		stroke = null;
		resetStrokeId();
	}

	public Sketch open() {
		if (sketch == null) {
			sketch = new Sketch();
		}
		return sketch;
	}

	private Sketch sketch = null;

	public void save(File file) {
		try {
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));

			bw.write(open().toString());
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Stroke stroke = null;

	public Stroke getCurrentStroke() {
		if (stroke == null) {
			stroke = new Stroke();
		}
		return stroke;
	}

	public void appendPoint(Point p) {
		getCurrentStroke().appendPoint(p);
	}

	public Stroke fetchStroke() {
		Stroke s = getCurrentStroke();
		s.setId(getStrokeId());
		stroke = null;
		return s;
	}

	public void clear() {
		init();
	}

	public void draw(Graphics2D g2) {
		open().draw(g2);
		getCurrentStroke().draw(g2);
	}

	public void drawCurrent(Graphics2D g2) {
		getCurrentStroke().drawLastPoint(g2);
	}
}
